<style lang="less">
@import './login.less';
</style>

<template>
  <div class="login" @keydown.enter="handleSubmit">
    <div class="login-con">
      <Card icon="md-log-in" title="欢迎登录青马游戏管理后台" :bordered="false">
        <div class="form-con">
          <Form ref="loginForm" :model="form" :rules="rules">
            <FormItem prop="username">
              <Input v-model="form.username">
                <span slot="prepend">
                  <Icon :size="16" type="ios-person"></Icon>
                </span>
              </Input>
            </FormItem>
            <FormItem prop="password">
              <Input type="password" v-model="form.password">
                <span slot="prepend">
                  <Icon :size="14" type="md-lock"></Icon>
                </span>
              </Input>
            </FormItem>
            <FormItem prop="server_code">
              <Select v-model="form.server_code">
                <Icon type="logo-buffer" slot="prefix" />
                <Option v-for="(item, key) in serverList" :value="key" :key="item.code">{{ item.name }}</Option>
              </Select>
            </FormItem>
            <FormItem class="margin-bottom-15">
              <Button type="primary" long :loading="loading" @click="handleSubmit">登录</Button>
            </FormItem>
          </Form>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { getServer } from '@/api/user'

export default {
  data () {
    return {
      form: {
        server_code: '',
        username: '',
        password: ''
      },
      serverList: [],
      rules: {
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        server_code: [
          { required: true, message: '请选择服务器', trigger: 'change' }
        ]
      },
      loading: false
    }
  },
  created () {
    let vm = this
    vm.getServer()
  },
  methods: {
    ...mapActions([
      'handleLogin'
    ]),
    getServer () {
      getServer().then(response => {
        this.serverList = response.data.data
      })
    },
    handleSubmit () {
      let vm = this
      let username = vm.form.username
      let password = vm.form.password
      let server_code = vm.serverList[vm.form.server_code]['code']
      vm.$refs.loginForm.validate((valid) => {
        if (valid) {
          vm.loading = true
          vm.handleLogin({ username, password, server_code }).then(() => {
            sessionStorage.setItem('ApiAdmin_AppInfo', '管理员')
            sessionStorage.setItem('Server_Name', vm.serverList[vm.form.server_code]['name'])
            vm.$router.push({
              name: 'home'
            })
            vm.loading = false
          }).catch(() => {
            vm.loading = false
          })
        }
      })
    }
  }
}
</script>
